//
//  ASWebController.m
//  AvatarShow
//
//  Created by xunruiIOS on 2021/4/27.
//

#import "ASWebController.h"
#import "ASAlertView.h"
#import <WebKit/WebKit.h>

@interface ASWebController () <WKUIDelegate,WKNavigationDelegate>

@end

@implementation ASWebController

- (void)dealloc{
    FELog(@"DFWebViewController 页面释放");
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BACKGROUND_COLOR;
    //self.navigationController.navigationBar.topItem.title = @"";
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.loadUrl]];
    [self.webView loadRequest:request];
    [self remeveLongPan];
    [self loadNetState];
}


///获取当前网络状态
-(void)loadNetState{
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *manager =  [AFNetworkReachabilityManager sharedManager];
    // 2.设置网络状态改变后的处理
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    // 当网络状态改变了, 就会调用这个block
    switch (status) {
        case AFNetworkReachabilityStatusUnknown: // 未知网络
            [self showNetErrAlert];
            break;
        case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
            [self showNetErrAlert];
            break;
        case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
            break;
        case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
            break;
        }
    }];
    // 3.开始监控
    [manager startMonitoring];
}

- (void)showNetErrAlert{
    ASAlertView *ale = [[ASAlertView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    UIWindow *win = [UIApplication sharedApplication].keyWindow;
    ale.titleLab.textAlignment = NSTextAlignmentCenter;
    [ale setContentStr: @"未能加入网络，请在“设置”中打开网络"];
    [win addSubview:ale];
    ale.clickSubBtnBlock = ^(NSInteger btnTag) {
        if (btnTag == 1) {
            NSURL *appSettings = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication] openURL:appSettings options:@{} completionHandler:^(BOOL success) {}];
        }
    };
}

/// 去掉webview的长按手势
- (void)remeveLongPan{
     //禁止长按弹出 UIMenuController 相关
      //禁止选择 css 配置相关
      NSString*css = @"body{-webkit-user-select:none;-webkit-user-drag:none;}";
      //css 选中样式取消
      NSMutableString*javascript = [NSMutableString string];
      [javascript appendString:@"var style = document.createElement('style');"];
      [javascript appendString:@"style.type = 'text/css';"];
      [javascript appendFormat:@"var cssContent = document.createTextNode('%@');", css];
      [javascript appendString:@"style.appendChild(cssContent);"];
      [javascript appendString:@"document.body.appendChild(style);"];
      [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择
      [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按

      //javascript 注入
      WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript
      injectionTime:WKUserScriptInjectionTimeAtDocumentEnd
      forMainFrameOnly:YES];
      WKUserContentController*userContentController = [[WKUserContentController alloc] init];
      [userContentController addUserScript:noneSelectScript];
      WKWebViewConfiguration*configuration = [[WKWebViewConfiguration alloc] init];
      configuration.userContentController = userContentController;
      //控件加载
      [self.webView.configuration.userContentController addUserScript:noneSelectScript];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if (self.backBlock) {
        self.backBlock();
    }
}

- (WKWebView *)webView{
    if (!_webView) {
        _webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:[WKWebViewConfiguration new]];
        _webView.backgroundColor = self.view.backgroundColor;
        _webView.allowsBackForwardNavigationGestures = NO;
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
    }
    return _webView;
}

#pragma mark 网页加载完成 延时0.2秒展示网页，，此时夜间模式的颜色已经修改完毕，，不会看到闪白了

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    self.webView.hidden = YES;
    [MBProgressHUD showMessage:@"加载中"];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    /// 延时0.2s 显示网页
    [self performSelector:@selector(showWebView) withObject:self afterDelay:0.2];
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    [MBProgressHUD hideHUD];
    self.webView.hidden = NO;
    [MBProgressHUD showError:@"加载失败"];
}


- (void)showWebView{
    self.webView.hidden = NO;
    [MBProgressHUD hideHUD];
    
    for (UIView* subview in self.webView.subviews) {
        for (UIGestureRecognizer* longPress in subview.gestureRecognizers) {
            if ([longPress isKindOfClass:UILongPressGestureRecognizer.class]) {
                [subview removeGestureRecognizer:longPress];
            }
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
